package com.yiwenup.leetcode.offer;

import com.yiwenup.leetcode.ListNode;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
 **/
public class No006 {

    /**
     * 执行用时：2 ms, 在所有 Java 提交中击败了38.74%的用户
     * 内存消耗：38.7 MB, 在所有 Java 提交中击败了92.05%的用户
     */
    public int[] reversePrint(ListNode head) {
        if (head == null) return new int[0];

        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }

        int[] res = new int[stack.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = stack.pop();
        }

        return res;
    }

    /**
     * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
     * 内存消耗：39.1 MB, 在所有 Java 提交中击败了38.12%的用户
     */
    public int[] reversePrint2(ListNode head) {
        // 获取链表总大小
        int size = 0;
        ListNode cur = head;
        while (cur != null) {
            size++;
            cur = cur.next;
        }

        int[] ints = new int[size];
        for (int i = size - 1; i >= 0 ; i--) {
            ints[i] = head.val;
            head = head.next;
        }

        return ints;
    }
}
